<?php
/**
 *+------------------
 * Lflow
 *+------------------
 * Copyright (c) 2023~2030 gitee.com/liu_guan_qing All rights reserved.本版权不可删除，侵权必究
 *+------------------
 * Author: Mr.April(405784684@qq.com)
 *+------------------
 */
declare (strict_types=1);

namespace lflow\access\DB;

use ReflectionClass;

/**
 * 数据库操作帮助类
 *
 * @author Mr.April
 * @since  1.0
 */
class PDOHelper
{
    /**
     * Entity 实体类映射
     *
     * @param array  $arr       数组
     * @param string $className class名称
     *
     * @return object
     */
    public static function arrayToSimpleObj(array $arr, string $className): object
    {
        try {
            //传递类名或对象进来
            $reflectionClass = new ReflectionClass($className);
            $obj             = $reflectionClass->newInstance();
            foreach ($arr as $key => $value) {
                //过滤验证class 是否包含key
                if ($reflectionClass->hasProperty($key)) {
                    $property = $reflectionClass->getProperty($key);
                    $property->setAccessible(true);//私有属性需要设置允许访问
                    $property->setValue($obj, $value);
                }
            }
            return $obj;
        } catch (\ReflectionException $e) {
            throw new WorkFlowException($e->getMessage());
        }
    }

    /**
     * 对象class 获取
     *
     * @param string|object|null $clazz
     *
     * @return string
     */
    public static function getClassName(string|null|object $clazz): string
    {
        if (is_object($clazz)) {
            $clazz = new ReflectionClass($clazz);
            return $clazz->name;
        }
        return $clazz;
    }

}